package web.security;

/**
 * Created by aceyin on 15/6/22.
 */
public class JwtClaim {
    private static final String USER_IDENTITY_TPL = "%s__%s";
    private static final String USER_IDENTITY_REGEX = "(-?\\d+)__(.+)";
    public static final JwtClaim EMPTY = new JwtClaim(0l, "");
    private long userid;
    private String token;

    public JwtClaim(long userid, String token) {
        this.userid = userid;
        this.token = token;
    }

    @Override
    public String toString() {
        String s = String.format(USER_IDENTITY_TPL, String.valueOf(userid), token);
        return s;
    }

    public static JwtClaim from(String claimStr) {
        if (!claimStr.matches(USER_IDENTITY_REGEX)) {
            return EMPTY;
        }
        String uid = claimStr.replaceAll(USER_IDENTITY_REGEX, "$1");
        String pwd = claimStr.replaceAll(USER_IDENTITY_REGEX, "$2");
        try {
            JwtClaim claim = new JwtClaim(Long.parseLong(uid), pwd);
            return claim;
        } catch (Exception e) {
            e.printStackTrace();
            return EMPTY;
        }
    }

    public long getUserid() {
        return userid;
    }


    public String getToken() {
        return token;
    }

}
